package com.example.pattern.singleton;

public class LazyDoubleCheckSingleton {

    private volatile static LazyDoubleCheckSingleton singleton = null;

    private LazyDoubleCheckSingleton() {
    }

    //双重检查锁单例模式
    public static LazyDoubleCheckSingleton getInstance() {
        if (singleton == null) {
            synchronized (LazyDoubleCheckSingleton.class) {
                if (singleton == null) {
                    singleton = new LazyDoubleCheckSingleton();
                    //1、分配内存给这个对象
                    //2、初始化对象
                    //3、设置lazy指向刚分配的内存地址
                }
            }
        }
        return singleton;
    }

}

class ExecutorThread1 implements Runnable {
    @Override
    public void run() {
        LazyDoubleCheckSingleton instance = LazyDoubleCheckSingleton.getInstance();
        System.out.println(Thread.currentThread().getName() + ":" + instance);
    }
}

class Main1 {
    public static void main(String[] args) {
        //第一个线程验证为 null，第二个线程也验证为 null
        Thread t1 = new Thread(new ExecutorThread1());
        Thread t2 = new Thread(new ExecutorThread1());
        t1.start();
        t2.start();
        System.out.println("End");
        //End
        //Thread-0:com.example.LazyDoubleCheckSingleton@43cc9a51
        //Thread-1:com.example.LazyDoubleCheckSingleton@43cc9a51
    }
}